import random,time,requests,json

# from db import db
from model.models import db
from flask import Blueprint, request, jsonify, send_file, redirect
from flask_restful import Api, Resource,reqparse
from captcha.image import ImageCaptcha
from utils.myredis import r
from utils.sms import send_message, get_ali_object
from utils.myjwt import myjwt
from model.models import *

vip_dp = Blueprint('vip_dp', __name__)

api = Api(vip_dp)

@vip_dp.route("/buy",methods=['POST'])
def getviplist():
    data = json.loads(request.data)
    userid = data["userid"]
    year = data["year"]
    money = 200
    tmoney = money * int(year)
    order_no = str(int(time.time()))+str(userid)+str(random.randint(100,999))
    vip = VipRecord(userid=userid,year=year,money=tmoney,active_money=tmoney,status=1,order_no=order_no)
    db.session.add(vip)
    db.session.commit()
    # 支付
    alipay = get_ali_object()
    # 生成支付的url
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买vip服务",  # 商品简单描述
        out_trade_no=order_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=float(tmoney),  # 交易金额(单位: 元 保留俩位小数)
    )
    # 支付宝网关地址（沙箱应用）
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(
        query_params)
    pkey = 'orderpayfail'
    r.sortedset_add(pkey, order_no, int(time.time()))
    return jsonify({"code": 200, 'url': pay_url})

